#include "database.h"

Database::Database(QObject *parent) :
    QObject(parent)
{

}

void Database::getDoc(Document* doc)
{
    if (query.exec("SELECT type,number,client,date,payed,closed FROM document WHERE ID="+
                   QString().number(doc->ID)))
    {
        query.next();
        doc->type = query.record().value("type").toInt();
        doc->number = query.record().value("number").toInt();
        doc->client = query.record().value("client").toInt();
        doc->date = query.record().value("date").toDate();
        doc->payed = query.record().value("payed").toBool();
        doc->closed = query.record().value("closed").toBool();

        doc->total = 0;
        if (query.exec("SELECT ID,product,qty,price FROM document_row WHERE document="+
                       QString().number(doc->ID)))
        {
            while (query.next())
            {
                int rid = query.record().value("ID").toInt();
                doc->rows.insert(rid,new DocumentRow(doc));
                doc->rows[rid]->ID = rid;

                doc->rows[rid]->product = query.record().value("product").toInt();
                doc->rows[rid]->qty = query.record().value("qty").toInt();
                doc->rows[rid]->price = query.record().value("price").toDouble();
                doc->rows[rid]->amount = doc->rows[rid]->price * doc->rows[rid]->qty;
                doc->total += doc->rows[rid]->amount;
            }
        }

    }
}

QString Database::getClientName(int cl)
{
    QString s="";
    if (query.exec("SELECT name FROM clients WHERE ID="+
                   QString().number(cl)))
    {
        query.next();
        s= query.record().value("name").toString();
    }
    return s;
}
QString Database::getProductName(int cl)
{
    QString s="";
    if (query.exec("SELECT name FROM product WHERE ID="+
                   QString().number(cl)))
    {
        query.next();
        s= query.record().value("name").toString();
    }
    return s;
}

QString Database::getDocumentType(int cl)
{
    QString s="";
    if (query.exec("SELECT type FROM document_type WHERE ID="+
                   QString().number(cl)))
    {
        query.next();
        s= query.record().value("type").toString();
    }
    return s;
}

int Database::docRowCount(int id)
{
    int r=0;
    if (query.exec("SELECT COUNT(*) FROM document_row WHERE document="+
                   QString().number(id)))
    {
        query.next();
        r = query.record().value(0).toInt();
    }
}
//qDebug() << "rows="<<r;
